#include<16f877a.h>
//#device ADC=10
#include<stdlib.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=11592000)
//#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
unsigned int x_dir=0,y_dir=0,z_dir=0;
#define SELECT 0
#define HIGH 1
#define LOW 0
#define MOT1 PIN_C6
#define MOT2 PIN_C7
#define RF_A  PIN_B0
#define RF_B  PIN_B1
#define RF_C  PIN_B2
#define RF_D  PIN_B3
//#define MOT3 PIN_C2
//#define MOT4 PIN_C3
#define row1() init_lcd(0x80)	/* Begin at Line 1 */
#define row2() init_lcd(0xC0)   /* Begin at Line 2 */
#define LCD_Clear() init_lcd(0x01)	/* Clear display LCD */
unsigned char w[] = { 0x38,0x0c,0x01,0x06,0x80};
//unsigned int adc_val=0;


/*======================================================LCD Initialisation============================================*/
void init_lcd(unsigned char j)
{
   output_e (0x00);
   output_d (j);
   output_e (0x02);
   delay_ms (2);
   output_e (0x00);
   delay_ms (2);
}
/*=======================================================Display Function=============================================*/
void display(char s)
{
   output_e (0x01);
   output_d (s);
   output_e (0x03);
   delay_ms (2);
   output_e (0x01);
   delay_ms (2);
}
/*=======================================================Functions For ROW============================================*/
void Lcd_init()
{
unsigned char i=0;
   for( i = 0 ; i < 6 ; i++ )
   {
      init_lcd (w[i]);
   }
}

void forward()
 {
output_bit(MOT1,HIGH);
output_bit(MOT2,LOW);
//output_bit(MOT3,LOW);
//output_bit(MOT4,HIGH);
 }
void reverse()
 {
output_bit(MOT1,LOW);
output_bit(MOT2,HIGH);
//output_bit(MOT3,HIGH);
//output_bit(MOT4,LOW);
 }
void stop()
 {
output_bit(MOT1,LOW);
output_bit(MOT2,LOW);
//output_bit(MOT3,LOW);
//output_bit(MOT4,LOW);
 }


void main()
{
   port_b_pullups(true);
   Lcd_init();
   row1();
   display("Crane Control");
   setup_port_A(ALL_ANALOG);
   setup_adc(ADC_CLOCK_INTERNAL);
   output_b(0xff);
   while(1)
   {

      set_adc_channel(0);
      delay_us(20);
      y_dir=Read_ADC();
      //if(y_dir>=180)
      if(input(RF_A)==LOW)
      {
      row2();
      display("Reverse Direction");
      reverse();
      //delay_ms(10);
     
      //delay_ms(100);


      }
      //else if(y_dir<=158)
      else if(input(RF_B)==LOW)
      {
      row2();
      display("Forward Direction");
       forward();
      //delay_ms(10);
      
      //delay_ms(100);
      }
       //else if(y_dir>=159 && y_dir<=179)
      else if(input(RF_C)==LOW) //if(y_dir>=168 && y_dir<=174)
      {
      row2();
      display("Stable Condition");
      //delay_ms(10);
      stop();
      //delay_ms(100);
      }



      //printf("adc val=%u\n",y_dir);
      delay_ms(300);

      output_b(0xff);

   }


}
